#!/usr/bin/python
# -*- coding:utf-8 -*-
# @author  : 龍皓
# @time    : 2024/12/19 09:33
# @function: 多线程工具类
# @version : 1.0.0
import queue
import threading
import time


class ThreadUtil:
    def __init__(self, max_threads=10):
        # 线程列表
        self.threads = []
        # 线程锁
        self.lock = threading.Lock()
        # 最大线程数,默认为10
        self.max_threads = max_threads
        # 队列
        self.task_queue = queue.Queue()

    def add_task(self, target, args=None):
        """
        添加一个线程任务到任务队列

        Args:
            target:  线程要执行的目标函数
            args: 传递给目标函数的参数，可选，默认为None

        Returns:
        """
        if args is None:
            args = []
        task_info = {
            'target': target,
            'args': args
        }
        self.task_queue.put(task_info)

    def start_all(self):
        """
        启动所有添加的线程

        Returns:
        """
        while not self.task_queue.empty():
            with self.lock:
                if len(self.threads) < self.max_threads:
                    task_info = self.task_queue.get()
                    thread = threading.Thread(
                        target=self._execute_task,
                        args=(task_info['target'], task_info['args'])
                    )
                    self.threads.append(thread)
                    thread.start()
                else:
                    time.sleep(1)  # 若线程数已满，等待1秒后再尝试添加线程

    def join_all(self):
        """
        等待所有线程执行完毕

        Returns:
        """
        with self.lock:
            for thread in self.threads:
                thread.join()

    def _execute_task(self, target, args):
        """
        内部方法，用于执行具体的线程任务，并进行异常处理

        :param target: 要执行的目标函数
        :param args: 传递给目标函数的参数
        """
        try:
            target(*args)
        except Exception as e:
            print(f"线程任务执行出现异常: {e}")

def get_thread(max_threads=10):
    """获取多线程实例"""
    return ThreadUtil(max_threads=max_threads)